# -*- coding: utf-8 -*-
# encoding: utf-8
class IndexController < ApplicationController
  before_filter :employee_authorize,:except =>[:login,:validate_user,:index,:index1,:index2,:index3,:setPrivilegeToSession,:login2]
  before_filter :sys_before_log,:except =>[:login]
  before_filter :employee_action_hx,:except =>[:index,:validate_user,:login]
  before_filter :privilege_filter ,:except =>[:index,:index1,:index2,:index3,:login,:validate_user,:setPrivilegeToSession,:logout,:login2]

  def index
    if session[:employee_id] == nil
      redirect_to '/index/login'
    else
      @menus = getMenus()
      @companyNameAB = SysParam.find_by_company_id(session[:company_id]).company_name_ab
    end
  end
  
  def index1


  end

  
  def index3
    companyId = session[:company_id]
    roleId = session[:role_id]

    #先取得可以显示的模块
    rolesPrivilegeDetails = RolesPrivilegeDetail.find(:all,:select=>"DISTINCT module_id", :conditions=>["role_id = ? AND company_id = ? AND is_locked = 0",roleId,companyId])
    logger.info "My Module.........................................................."
    #在循环之前，先把权限细节都加载到Session中。
    #setPrivilegeToSession
    @items = ""
    #循环系统权限模块生成模块菜单
    logger.info "-----------------rolesPrivilegeDetails.length-----------------------"
    logger.info rolesPrivilegeDetails.length

    rolesPrivilegeDetails.each do |sysModule|
      logger.info "-----------------sysModule-----------------------"
      logger.info sysModule.module_id
      @items = @items +
        "{title: '#{sysModule.module.name}',
              //html: '&lt;empty panel&gt;11111',
              cls:'empty',
              items:[{
                  xtype: 'treepanel',
                  id: 'tree-panel-#{sysModule.module_id}',
                  region: 'center',
                  margins: '2 2 0 2',
                  autoScroll: true,
                  rootVisible: false,
                  useArrows: false,
                  lines:false,
                  border: false,
                  root:new Ext.tree.AsyncTreeNode({
                    id:'root',
                    text:'根节点',
                    expanded:true,
                    leaf:false,
                    children:["
      #从这儿开始循环菜单
      roleMenus = RolesPrivilegeDetail.find(:all,:select=>"DISTINCT menu_id",:conditions=>["module_id = ? AND is_locked = 0 AND role_id = ?",sysModule.module_id,roleId])
      menuStr = ""
      logger.info "+++++++++++++++roleMenus Size+++++++++++++++"
      logger.info roleMenus.size
      roleMenus.each do |roleMenu|
        logger.info "roleMenu.menu:"
        logger.info roleMenu.menu
        logger.info roleMenu.menu.id
        logger.info "roleMenu.menu.sys_controller:"
        logger.info roleMenu.menu.sys_controller
        logger.info roleMenu.menu.sys_controller.name
        logger.info roleMenu.menu.sys_action.name
        menuStr = menuStr + "{
                        id:'tree_item_#{roleMenu.menu_id}',
                        text:'#{roleMenu.menu.name}',
                        leaf:true,
                        listeners: {
                          'click': function(node, checked){
                            workTabs.add({
                              title: '#{roleMenu.menu.name}',
                              id:'tab_item_#{roleMenu.menu_id}',
                              autoLoad: {
                                url: '/#{roleMenu.menu.sys_controller.name}/#{roleMenu.menu.sys_action.name}',
                                scripts: true
                              },
                              closable:true
                            })
                            workTabs.setActiveTab('tab_item_#{roleMenu.menu_id}');
                          }
                        }
                      },"
      end
      menuStr = menuStr[0,menuStr.size-1]
      #在这儿结束菜单循环
      @items = @items + menuStr + " ]
                  })
                }]
            },"
    end
    @items = @items[0,@items.size-1]
    #logger.info @items

  end

  
  def login
    @imageNumber = rand(24)
  end

  def logout
    reset_session
    info="退出成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #验证用户是否可以登录
  def validate_user
    begin
      loginId = params[:user_name]
      password = params[:pwd]
      companyId = params[:company_id]
      employee = Employee.find(:first,:conditions => ["company_id = ? AND login_id = ? AND password = ? AND is_locked <> 1",companyId,loginId,password])

      if employee == nil
        #登录失败也记录一下。
        LoginLog.recordLoginInfo(nil,nil,nil, loginId , password , request.remote_ip ,nil)
        info="登录失败!"
      else
        session[:employee_id] = employee.id
        session[:employee_name] = employee.name
        session[:company_id] = employee.company_id
        session[:department_id] = employee.department_id
        session[:role_id] = employee.role_id
        session[:role] = employee.role
        session[:financial_management] = employee.role.financial_management
        session[:check_cost_price] = employee.role.check_cost_price
        session[:unsafe_discount_audit] = employee.role.unsafe_discount_audit
        session[:employee] = employee
        session[:department] = Department.find(employee.department_id)
        #登录成功记录一下。
        LoginLog.recordLoginInfo(session[:company_id], session[:department_id], session[:employee_id], loginId , password , request.remote_ip ,nil)
        info = "成功"
      end
      
      result = "{success:true,info:'#{info}'}"
      logger.info result
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.info "----------------------Exception--------------------------"
      logger.info e
    end
  end

  private
  #把权限细节加载到Session中
  def setPrivilegeToSession
    logger.info "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    roleId = session[:role_id]
    companyId = session[:company_id]
    privilegeDetails = PrivilegeDetail.find_by_sql("select pd.* from roles_privilege_details rpd,privilege_details pd where rpd.menu_id = pd.privilege_id AND rpd.role_id = #{roleId} AND rpd.company_id = #{companyId} AND rpd.is_locked = 0 AND pd.is_locked = 0")
    #logger.info privilegeDetails[0].attributes
    session[:privilege_details] = privilegeDetails
  end

  private


  def getMenus
    logger.info "------------------index--getMenus----------------------"
    companyId = session[:company_id]
    roleId = session[:role_id]

    #这是新形势的菜单，先抓取模块，再一条条的抓取详细的菜单。
    #总菜单
    #totalMenuArray <-- moduleMenuHash <-- subMenuArray <-- subMenuHash
    totalMenuArray = Array.new
    #rolesPrivilegeDetails = RolesPrivilegeDetail.find(:all,:select=>"DISTINCT module_id", :conditions=>["role_id = ? AND company_id = ? AND is_locked = 0",roleId,companyId])
    rolesPrivilegeDetails = RolesPrivilegeDetail.find(:all,:include=>[:module],:select=>"DISTINCT rpd.module_id",:conditions=>["p.parent_id = 0"],:joins=>" as rpd left join privileges as p on rpd.role_id = #{roleId} AND rpd.company_id = #{companyId} AND rpd.is_locked = 0 AND rpd.module_id = p.id",:order=>"p.sort_id")
    rolesPrivilegeDetails.each do |sysModule|
      moduleMenuHash = Hash.new
      moduleMenuHash[:name] = sysModule.module.name
      moduleMenuHash[:image] = '/images/system/plugin.gif'
      moduleMenuHash[:leaf] = false
      #开始生成菜单
      #roleMenus = RolesPrivilegeDetail.find(:all,:select=>"DISTINCT menu_id",:conditions=>["module_id = ? AND is_locked = 0 AND role_id = ?",sysModule.module_id,roleId],:order=>"sort_id")
      roleMenus = RolesPrivilegeDetail.find(:all,:select=>"DISTINCT rpd.menu_id",:conditions=>["rpd.module_id = ? AND rpd.is_locked = 0 AND rpd.role_id = ?",sysModule.module_id,roleId],:joins=>"as rpd left join privileges as p on rpd.menu_id = p.id",:order=>"p.sort_id")
      subMenuArray = Array.new
      roleMenus.each do |roleMenu|
        subMenuHash = Hash.new
        #subMenuHash[:id] = roleMenu.menu.id
        subMenuHash[:text] = roleMenu.menu.name
        subMenuHash[:url] = "#{roleMenu.menu.sys_controller.name}/#{roleMenu.menu.sys_action.name}"
        subMenuHash[:id] = "#{roleMenu.menu.sys_controller.name}/#{roleMenu.menu.sys_action.name}"
        subMenuHash[:icon] = '/images/system/plugin.gif'
        subMenuHash[:leaf] = true
        subMenuArray << subMenuHash
        logger.info "#{roleMenu.menu.sys_controller.name}/#{roleMenu.menu.sys_action.name}"
      end
      moduleMenuHash[:children] = subMenuArray

      totalMenuArray << moduleMenuHash
    end
    logger.info "totalMenuArray............................."
    menus = totalMenuArray.to_json
    return menus
  end
  
end
